<?php

namespace App\Console\Commands;

use App\Http\Controllers\Front\WeChatController;
use App\Model\Enterprise;
use App\Model\EnterpriseUserCommissionDetails;
use App\Model\UserRecharge;
use App\Model\UserWeixinPayCallBackErrorLog;
use App\Model\WeChat;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use EasyWeChat\Factory;

/**
 * 企业队列返佣
 * Class EnterpriseUserCommissionDetailsQueue
 * @package App\Console\Commands
 */
class EnterpriseUserCommissionDetailsQueue extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'enterprise_user_commission_details_queue';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        while (1) {
            // 查询 公司返佣详情表 status为0 的
            $result = EnterpriseUserCommissionDetails::where('status', '0')->first();
            if ($result) {
                try {
                    \DB::beginTransaction();
                    // 查询该企业
                    $enterprise = Enterprise::where('id', $result->relation_id)->first();
                    if (!empty($enterprise)) {
                        // 修改企业表佣金
                        $enterprise->increment('fenxiao_reward_gold_current', $result->money);
                        $enterprise->increment('fenxiao_reward_gold_total', $result->money);
//                    $enterprise->save();

                        // 修改队列表的状态为1
                        $result->status = 1;
                        $result->save();

                        \DB::commit();
                    } else {
                        \DB::rollBack();
                    }
                } catch (\Exception $e) {
                    \DB::rollBack();
                    // 记录错误日志
                    $error_log = new UserWeixinPayCallBackErrorLog();
                    $error_log->insert(['error' => $e->getMessage()]);
                }
            } else {
                echo 'game over';
                sleep(10);
            }
        }
    }
}
